/****************************************************
File Name:  qsort.cpp
Author:     Animesh Sharma
Date:       11/2005
Description:    Source code for Quicksort Algorithm - Array based Implementation(Project 3 cs352)
Submission Date: 1st Dec 2005
Project Due Date: 1st Dec 2005
****************************************************/


#include <iostream>  
#include <cstring>   
#include <fstream>
#include <ctype.h>
using namespace std;

int ccount=0;
int wcount=0;
int lcount=0;

int main(int argc,char *argv[])
{
	if (argc!=2) {
		cout << "usage: qsort file.txt" << endl;
		exit(1);
	}
	ifstream input(argv[1]);
	if (input.fail()) {
		cout << "error: could not open file " << argv[1] << endl;
		exit(1);
	}
	int c;
	int inword=0;
	c = input.get();
	while (!input.eof()) {
		if (isalnum(c))
			inword=1;
		else if (inword==1) {
			wcount++;
			inword=0;
		}
		if (c=='\n')
			lcount++;
		ccount++;
		c = input.get();
	}
	input.close();
    char *allwords[wcount];  // array of POINTERS to char strings
    char word[500];        // input buffer for longest possible word.
    int n = 0;           // count of number of words.
	ifstream fileo(argv[1]);
    // read words/tokens from input stream
    while (fileo >> word) {
        allwords[n] = new char[strlen(word)+1]; // allocate space
        strcpy(allwords[n], word);      // copy word to new space
        n++;
    }

    cout << "Number of words = " << n << endl;

    // write out all the words in reverse order.
    //    The dynamically allocated space is freed after the word
    //    is printed, and the pointer is set to NULL.  This isn't
    //    necessary here because the program immediately terminates,
    //    but it's a good, safe practice.
    for (int i=n-1; i>=0; i--) {
//        cout << allwords[i] << endl; // print the word
        delete [] allwords[i];       // free space
        allwords[i] = NULL;          // remove pointer
    }
   	fileo.close();
	return(0);
}


